import { nearest_data } from "../lib/nearest.mjs";
import thin_render from "../lib/thin_render.mjs";
import validate from "../lib/validate.mjs";
import viewmode from "../lib/viewmode.mjs";

export default function ({ container, template }) {
  console.log({ container, template });
  let mode = template.mode || viewmode(container);

  let el = document.createElement("wizard");
  let el_hidden = document.createElement("input");
  el_hidden.style.display = "none"; // 使用CSS隐藏而不是type=hidden
  el.appendChild(el_hidden);

  if (template?.must_finish === false) {
  } else {
    el_hidden.setAttribute("name", "wizard_finishstatus");
    el_hidden.setAttribute("required", "required");
    el_hidden.value = "not_finished";
    el_hidden.setAttribute("pattern", "finished");
    el_hidden.setCustomValidity("请完成所有步骤"); // 设置初始验证消息
  }
  // 检查wizard是否为空
  const hasWizard = template.wizard && Object.keys(template.wizard).length > 0;

  // 如果是只读模式且有wizard，直接显示最后一个step的内容
  if (mode === "read" && hasWizard) {
    container.appendChild(el);
    const steps = Object.keys(template.wizard);
    const lastStep = template.wizard[steps[steps.length - 1]];
    let el_content = document.createElement("content");
    el.appendChild(el_content);
    thin_render(el_content, lastStep.template || []);
    return;
  }

  template?.init?.({ container, data: nearest_data(container) });

  container.appendChild(el);

  // 如果wizard为空，只显示内容
  if (!hasWizard) {
    let el_content = document.createElement("content");
    el.appendChild(el_content);
    thin_render(el_content, template.div || []);
    return;
  }

  let current_step = 0;
  let total_steps = Object.keys(template.wizard).length;
  let steps = Object.keys(template.wizard);

  // 预先声明按钮变量
  let btn_prev, btn_next, btn_finish;

  // 切换到指定步骤
  async function switchToStep(targetStep, isForward = false) {
    if (targetStep >= current_step) return; // 不允许向前跳转
    if (targetStep < 0) return; // 不允许小于0

    let valid = true;

    // 只有向前时才调用after钩子
    if (isForward) {
      const currentStep = template.wizard[steps[current_step]];
      if (currentStep.after)
        valid = await currentStep.after({
          container,
          data: nearest_data(container),
        });
    }

    if (template?.must_finish === false) {
    } else {
      el_hidden.value = "not_finished";
      el_hidden.setCustomValidity("请完成所有步骤"); // 重置验证消息
    }

    if (valid !== false) {
      current_step = targetStep;
      updateContent();
    }
    return;
  }

  // 更新内容区域的函数
  async function updateContent() {
    let step = template.wizard[steps[current_step]];
    // 调用当前步骤的before钩子
    if (step && step.before) {
      await step.before({
        container,
        data: nearest_data(container),
      });
    }

    el_content.innerHTML = `
      ${step && step.description ? `<p>${step.description}</p>` : ""}
    `;
    thin_render(el_content, (step && step.template) || []);

    // 更新步骤状态
    el_steps.querySelectorAll("step").forEach((step, index) => {
      if (index === current_step) {
        step.classList.add("active");
      } else {
        step.classList.remove("active");
      }

      // 更新步骤的可点击状态
      if (index < current_step) {
        step.classList.add("clickable");
      } else {
        step.classList.remove("clickable");
      }
    });

    // 更新按钮状态
    btn_prev.disabled = current_step <= 0;
    btn_next.disabled = current_step >= total_steps - 1;

    // 如果存在finish钩子，显示完成按钮
    if (template.finish) {
      const isLastStep = current_step === total_steps - 1;
      btn_finish.style.display = isLastStep ? "" : "none";
      btn_next.style.display = isLastStep ? "none" : "";
      // 在最后一步时重新激活完成按钮
      if (isLastStep) {
        btn_finish.disabled = false;
      }
    }
    return;
  }

  let el_steps = document.createElement("steps");
  el.appendChild(el_steps);
  for (let step of steps) {
    let el_step = document.createElement("step");
    el_step.innerHTML = `
      <h4>${template.wizard[step].title || step}</h4>
    `;
    // 添加点击事件
    el_step.onclick = function () {
      const index = Array.from(el_steps.children).indexOf(this);
      switchToStep(index);
    };
    el_steps.appendChild(el_step);
  }

  let el_content = document.createElement("content");
  el.appendChild(el_content);

  let el_pager = document.createElement("pager");
  el.appendChild(el_pager);

  // 创建上一步按钮
  btn_prev = document.createElement("button");
  btn_prev.textContent = "上一步";
  btn_prev.onclick = () => {
    if (current_step > 0) {
      switchToStep(current_step - 1, false);
    }
  };
  el_pager.appendChild(btn_prev);

  // 创建下一步按钮
  btn_next = document.createElement("button");
  btn_next.textContent = "下一步";
  btn_next.onclick = () => {
    validate({
      container: container,
      ignoreinsertrow: true,
      ignorewizardfinishstatus: true,
      valid: async () => {
        if (current_step < total_steps - 1) {
          // 调用当前步骤的after钩子
          const currentStep = template.wizard[steps[current_step]];
          let valid = true;
          if (currentStep && currentStep.after)
            valid = await currentStep.after({
              container,
              data: nearest_data(container),
            });

          if (valid !== false) {
            current_step++;
            updateContent();
          }
        }
      },
      invalid: () => {
        console.log("invalid");
      },
    });
  };
  el_pager.appendChild(btn_next);

  // 如果存在finish钩子，创建完成按钮
  if (template.finish) {
    btn_finish = document.createElement("button");
    btn_finish.textContent = "完成";
    btn_finish.style.display = "none"; // 初始隐藏
    btn_finish.onclick = () => {
      btn_finish.disabled = true; // 禁用按钮防止重复点击
      if (template?.must_finish === false) {
      } else {
        el_hidden.value = "finished";
        el_hidden.setCustomValidity(""); // 清除验证消息
      }
      template.finish({ container, data: nearest_data(container) });
    };
    el_pager.appendChild(btn_finish);
  }

  updateContent();
}
